package com.ch.common.base.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView

/**
 *
 * 两个泛型，T代表item的model类型即itemList的bean类型，
 * mTBinding代表itemLayout对应生成的XXXBinding类
 * brId则对应itemLayout里相应variable的变量名，
 * 比如variable的name是hogan，brId就是BR.hogan
 *
 **/
abstract class BaseRecycleAdapter<T, mTBinding : ViewDataBinding>(
    private val itemList: List<T>,
    private val brId: Int
) : RecyclerView.Adapter<BaseRecycleAdapter<T, mTBinding>.ViewHolder>() {
    protected var mContext: Context? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        if (mContext == null) {
            mContext = parent.context
        }
        val binding: mTBinding =
            DataBindingUtil.inflate(LayoutInflater.from(mContext), getLayoutId(), parent, false)
        val holder = ViewHolder(binding.root)
        holder.binding = binding
        return holder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.binding.setVariable(brId, itemList[position])
        //立即执行绑定，在对view变化时效敏感的地方常用，不加这句有可能出现itemView更新滞后、闪烁等问题
        holder.binding.executePendingBindings()
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    //获取具体子adapter对应的itemLayoutId
    abstract fun getLayoutId(): Int

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        lateinit var binding: mTBinding
    }
}